<template>
  <div class="custom-quality-engineering-container page-common-layout">
    <div class="screen-conditions-container">
      <a-select
        showSearch
        :filter-option="filterOption"
        v-model="condition.tenantCode"
        :loading="projectLoading"
        placeholder="请选择项目名称"
        class="project-select"
      >
        <a-select-option
          :value="item.proCode"
          v-for="item in projectSoucre"
          :key="item.uuid"
        >
          {{ item.proName }}
        </a-select-option>
      </a-select>
      <a-select
        showSearch
        :filter-option="filterOption"
        :loading="projectTypeLoading"
        placeholder="请选择项目类型"
        v-model="condition.proType"
      >
        <a-select-option
          :value="item.dicItemCode"
          v-for="item in projectTypeSoucre"
          :key="item.uuid"
        >
          {{ item.dicItemName }}
        </a-select-option>
      </a-select>
      <a-select
        showSearch
        :filter-option="filterOption"
        placeholder="请选择状态"
        v-model="condition.approveStatus"
      >
        <a-select-option value="1"> 审批中 </a-select-option>
        <a-select-option value="2"> 审批通过 </a-select-option>
        <a-select-option value="3"> 驳回 </a-select-option>
      </a-select>
      <div class="group-button">
        <a-button class="cu-btn-primary" icon="search" @click="search()">
          查询
        </a-button>
        <a-button class="cu-btn-filter" icon="reload" @click="reset()">
          重置
        </a-button>
      </div>
    </div>
    <div class="table-container">
      <div class="header" header="品质工程审批">
        <a-button
          @click="gotoAdd()"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-action:xmsqsp_add
        >
          新增
        </a-button>
        <!-- <a-button
          @click="openModal()"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
        >
          测试BIM图库上传
        </a-button> -->
      </div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="proName" title="项目名称"> </vxe-column>
          <vxe-column field="proTypeeDesc" title="项目类型"> </vxe-column>
          <vxe-column field="gradeDesc" title="评级"> </vxe-column>
          <vxe-column field="startDate" title="申请时间"> </vxe-column>
          <vxe-column field="applicant" title="申请人"> </vxe-column>
          <vxe-column title="状态">
            <template #default="{ row }">
              <div class="status">
                <div :class="[checkStatusClass(row), 'status-icon']"></div>
                <div class="status-name">{{ checkStatusName(row) }}</div>
              </div>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            width="220"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  type="link"
                  v-for="(item, index) in row.normalBtns"
                  :key="index"
                  @click="eventDispacth(item.event, row)"
                  :class="[item.label == '删除' && 'danger']"
                >
                  {{ item.label }}
                </a-button>
                <a-popover
                  v-if="row.popoverBtns.length > 0"
                  overlayClassName="table-more-btns-popover"
                  placement="bottom"
                  :getPopupContainer="() => $el"
                >
                  <template slot="content">
                    <div
                      class="popover-btn"
                      v-for="(popBtn, index) in row.popoverBtns"
                      :key="index"
                      @click="eventDispacth(popBtn.event, row)"
                    >
                      {{ popBtn.label }}
                    </div>
                  </template>
                  <a-button type="link">...</a-button>
                </a-popover>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <addModal
      :visible.sync="addModalVisible"
      :parameter="dataSoucre"
      :key="addModalKey"
    ></addModal>

    <flowChat ref="flowChatForm"></flowChat>
    <comment-modal ref="commentModal"></comment-modal>

    <!-- 查看弹窗 -->
    <view-form
      ref="createModal"
      :visible="viewModalVisible"
      :loading="confirmLoading"
      :url="url"
      requestMethod="post"
      :tableDataType="tableDataType"
      :customFooter="modalFooter"
      :width="1400"
      @cancel="handleCancel()"
      :key="viewModalKey"
    />

    <uploadImage
      :visible.sync="imageVisible"
      @changeImg="changeImg"
    ></uploadImage>
  </div>
</template>

<script>
import addModal from "./components/addModal";
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
import flowChat from "@/pages/workflow/apiFlowableTask/myMission/flowChat.vue";
// 查看
import viewForm from "@/pages/form/formPreview/edit.vue";
import uploadImage from "@/pages/user/portalEntry/components/GIS/uploadImage";
import { axios } from "@/utils/request";
import { getPZGCProList } from "@/api/qualityEngineering";
import { mapGetters } from "vuex";
export default {
  components: {
    addModal,
    commentModal,
    flowChat,
    viewForm,
    uploadImage,
  },
  data() {
    return {
      imageVisible: false,
      //项目下拉框
      projectSoucre: [],
      projectLoading: false,
      //项目类型下拉框
      projectTypeSoucre: [],
      projectTypeLoading: false,
      condition: {
        //项目
        tenantCode: undefined,
        //责任主体
        proType: undefined,
        //状态
        approveStatus: undefined,
      },
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      addModalVisible: false,
      addModalKey: "add_modal_01",
      dataSoucre: {},
      viewModalVisible: false,
      viewModalKey: "view_modal_01",
      confirmLoading: false,
      url: {},
      tableDataType: "",
      tableUuid: "1387BAB062114BF98635C93463C77A26",
      formJsonData: "",
      modalFooter: {},
    };
  },
  computed: {
    ...mapGetters(["roles"]),
  },
  mounted() {
    this.getData();
    this.getButtonRoles();
  },
  methods: {
    getButtonRoles() {
      let { permissions } = this.roles;
      permissions.forEach((v) => {
        console.log(v.actionList);
      });
    },

    changeImg() {},
    openModal() {
      this.imageVisible = true;
    },

    // 流程图
    handleFlow(record) {
      this.$post("/workflow/oaLeave/clickFlowChart", {
        uuid: record.uuid,
      }).then((res) => {
        if (res.statusCode != 300) {
          const jsonData = res;
          this.$refs.flowChatForm.loadData(
            jsonData,
            jsonData.lists.actDeModelId,
            jsonData.lists.actDeModelKey,
            jsonData.lists.actDeModelName,
            jsonData.lists.flowDesign,
            record
          );
        } else {
          this.$message.error(res.message);
        }
      });
    },
    handleGetListComments(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },

    gotoAdd() {
      this.addModalKey = Date.now();
      this.dataSoucre = {
        text: "新增",
      };
      this.addModalVisible = true;
    },

    editorClick(row) {
      this.addModalKey = Date.now();
      this.dataSoucre = {
        text: "编辑",
        ...row,
      };
      this.addModalVisible = true;
    },
    handleCancel() {
      this.viewModalVisible = false;
    },
    async gotoView(row = {}) {
      this.viewModalKey = Date.now();
      let { uuid } = row;
      this.modalFooter = { footer: null };
      this.viewModalVisible = true;
      this.formJsonData = await this.loadDataJson();
      this.$refs.createModal.title = "查看";
      this.$refs.createModal.loading = true;
      this.$post("/form/formDatabase/formGetDetail", {
        uuid: uuid,
        formUuid: this.tableUuid,
      }).then((res) => {
        this.$refs.createModal.loadData(
          this.tableUuid,
          "view",
          this.dealData(true),
          res
        );
      });
    },
    loadDataJson() {
      return new Promise((reslove) => {
        this.$post("/form/formBasicConfigure/getDetailByUuid", {
          uuid: this.tableUuid,
        })
          .then((res) => {
            this.tableDataType = res.formDatabase?.type || "";
            reslove(res.formDesign.designJson);
          })
          .catch((_) => {
            reslove({});
          });
      });
    },
    dealData(disabled = false) {
      let dealData = JSON.parse(this.formJsonData);
      let { list = [] } = dealData;
      list.forEach((v) => {
        let { columns = [], options } = v;
        if (options) {
          options.disabled = disabled;
        }
        columns.forEach((item) => {
          let { list = [] } = item;
          list.forEach((c) => {
            let { options } = c;
            options.disabled = disabled;
          });
        });
      });
      this.formJsonData = JSON.stringify(dealData);
      return this.formJsonData;
    },

    getData() {
      Promise.all([
        this.getProjectData(),
        this.getProjectType(),
        this.getTableData(),
      ])
        .then((res) => {})
        .finally((_) => {});
    },
    //查询项目下拉框
    getProjectData() {
      this.projectLoading = true;
      return new Promise((resolve, reject) => {
        getPZGCProList({ type: 2 })
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            resolve();
          })
          .catch((_) => {
            this.condition.tenantCode = undefined;
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {
            this.projectLoading = false;
          });
      });
    },

    //项目类型
    getProjectType() {
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "projectType",
        })
          .then((res) => {
            let { data } = res;
            this.projectTypeSoucre = data || [];
            resolve();
          })
          .catch((_) => {
            this.projectTypeSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    search() {
      this.pager.page = 1;
      this.getTableData();
    },

    reset() {
      this.condition.tenantCode = undefined;
      this.condition.proType = undefined;
      this.condition.approveStatus = undefined;
      this.search();
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          axios
            .get(`/mdata/sysProject/deleteDataByUuid?uuid=${row.uuid}`, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let {
        approveStatus = "",
        tenantCode = "",
        proType = "",
      } = this.condition;
      axios
        .post(
          `/mdata/sysProject/getPZGCSPPageSet?pageNo=${page}&pageSize=${pageSize}`,
          {
            proCode: tenantCode,
            proType,
            approveStatus,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.tableData = res?.rows || [];
          this.pager.total = res?.totalCount || 0;
          this.tableData.forEach((v) => {
            let { normal = [], popover = [] } = this.filterTableButtons(v);
            v.normalBtns = normal;
            v.popoverBtns = popover;
          });
        })
        .catch((_) => {
          this.tableData = [];
          this.pager.total = 0;
        })
        .finally((_) => {
          this.loading = false;
        });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    //事件派发
    eventDispacth(eventName, params = {}) {
      if (!eventName) {
        return;
      }
      this[eventName](params);
    },

    //校验下发按钮是否展示
    filterTableButtons(row) {
      // 处理
      let buttons = [{ label: "查看", event: "gotoView" }];
      let result = {};
      let emuSource = {
        approve: [{ label: "审批", event: "" }],
        edit: [{ label: "编辑", event: "editorClick" }],
        delete: [{ label: "删除", event: "handleDelClick" }],
        flowInfo: [{ label: "流程图", event: "handleFlow" }],
        approveInfo: [{ label: "审批记录", event: "handleGetListComments" }],
      };
      Object.keys(emuSource).forEach((key) => {
        if (row[key] == true) {
          buttons = buttons.concat(emuSource[key]);
        }
      });
      if (buttons.length > 3) {
        const middle = 2;
        result = {
          normal: buttons.slice(0, middle),
          popover: buttons.slice(middle, buttons.length),
        };
      } else {
        result = {
          normal: buttons,
          popover: [],
        };
      }
      return result;
    },

    //校验状态名称
    checkStatusName(row) {
      let { approveStatus } = row;
      switch (approveStatus) {
        case "1":
          return "审批中";

        case "2":
          return "审批通过";

        case "3":
          return "驳回";

        default:
          return "--";
      }
    },
    //校验状态className
    checkStatusClass(row) {
      let { approveStatus } = row;
      switch (approveStatus) {
        case "1":
          return "warn";

        case "2":
          return "normal";

        case "3":
          return "error";

        default:
          return "";
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
.table-container {
  .own {
    color: #3759a0;
  }
  .status {
    display: flex;
    align-items: center;
    justify-content: center;
    .status-icon {
      margin-right: 4px;
      width: 8px;
      height: 8px;
      border-radius: 50%;
      flex-shrink: 0;
      background: #aab0bc;
      &.warn {
        background: #f07f17;
      }
      &.normal {
        background: #00c1b6;
      }
      &.error {
        background: #ff2d2d;
      }
    }
    .status-name {
      min-width: 60px;
    }
  }
}
/deep/.ant-popover {
  &.table-more-btns-popover {
    .ant-popover-inner-content {
      cursor: pointer;
      text-align: center;
      padding: 10px 0;
      .popover-btn {
        height: 30px;
        padding: 0 20px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        margin-bottom: 10px;
        color: #525a5d;
        &:last-child {
          margin: 0;
        }
        &:hover {
          background: #e9ecf3;
          color: @primary-color;
        }
      }
    }
  }
}
</style>
